<template>
    <div class="container">
        <div class="chat-wrapper" v-if="!show"><span @click.stop="show=!show"></span><span class="other"></span></div>
        <transition appear name="slide">
            <div v-if="show" class="chat-container" ref="chatcontainer"
                 :style="{'height': height+'px', 'margin-top': -(height/2)+'px'}">
                <div class="chat-arrow-wrapper"><span @click.stop="onshow"></span></div>
                <ul class="chat-list-wrapper">
                    <li class="search-box">
                        <label class="iconfont" for="serach">
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="12" height="12"
                                 style="fill: rgba(142,142,147,1);">
                                <path d="M955.417 913.102l-249.886-249.9c61.4-64.646 99.27-151.765 99.27-247.893 0-199.052-161.358-360.413-360.4-360.413-199.049 0-360.417 161.361-360.417 360.413 0 199.01 161.368 360.405 360.417 360.405 79.18 0 152.221-25.852 211.692-69.17l252.931 252.949c12.85 12.813 33.524 12.813 46.365 0 12.84-12.876 12.84-33.552.028-46.391zM444.4 717.033c-162.849 0-294.891-132.038-294.891-294.884 0-162.873 132.042-294.878 294.891-294.878 162.869 0 294.874 132.043 294.874 294.878 0 162.818-132.004 294.884-294.874 294.884z"/>
                            </svg>
                        </label>
                        <div class="search-wrapper">
                            <input class="search-input" type="text" id="serach" placeholder="搜索">
                            <span class="search-close"></span>
                        </div>
                        <span class="search-cancel">取消</span>
                    </li>
                    <template v-if="chatRoom.length">
                        <li class="chat-item" @click="inChat(item.id, item.roomName)" v-for="(item, index) in chatRoom" :key="index">
                            <img class="chat-item-img" :src="chatList[index % chatList.length].imgUrl" alt="">
                            <ul class="chat-info-wrapper">
                                <li class="chat-info">
                                    <span class="chat-name">{{item.roomName}}</span>
                                    <span>{{chatList[index].date}}</span>
                                </li>
                                <li class="chat-content">{{chatList[index].content}}</li>
                            </ul>
                            <span class="chat-item-close"></span>
                        </li>
                    </template>
                </ul>
                <div class="chat-room-wrapper">
                    <dialog-box @onsend="onsend" :roomRecord="roomRecord" :typeName="typeName"></dialog-box>
                </div>
            </div>
        </transition>
    </div>
</template>

<script>
    import DialogBox from '../../base/dialog-box/DialogBox'
    // import { prefixStyle } from '../../common/js/dom'
    import { getUserInfo } from "../../common/js/cache";
    import { getChatRoomRecord, sendAllWebSocket } from "../../api/home";
    import { ERROR_NO } from "../../util/config";

    // const transform = prefixStyle('transform')

    const defHeight = 874
    export default {
        props: {
            height: {
                type: Number,
                default: defHeight
            },
            chatRoom: {
                type: Array,
                default: () => []
            }
        },
        data () {
            return {
                init: false,
                chatList: [
                    {
                        imgUrl: 'https://img1.baidu.com/it/u=1207533529,3946480795&fm=26&fmt=auto&gp=0.jpg',
                        name: 'Java交流群',
                        date: '5分钟前',
                        content: '暂无新消息...'
                    },
                    {
                        imgUrl: 'https://img1.baidu.com/it/u=504609824,3604971623&fm=11&fmt=auto&gp=0.jpg',
                        name: 'Java交流群',
                        date: '5分钟前',
                        content: '暂无新消息...'
                    },
                    {
                        imgUrl: 'https://img2.baidu.com/it/u=1004953359,2131419137&fm=11&fmt=auto&gp=0.jpg',
                        name: 'Java交流群',
                        date: '5分钟前',
                        content: '暂无新消息...'
                    },
                    {
                        imgUrl: 'https://img1.baidu.com/it/u=3431148336,543389674&fm=11&fmt=auto&gp=0.jpg',
                        name: 'Java交流群',
                        date: '5分钟前',
                        content: '暂无新消息...'
                    }
                ],
                show: false,
                chatRoomList: [],
                typeName: '',
                roomRecord: {}
            }
        },
        methods: {
            onshow () {
                this.show = !this.show
                this.$emit('onshow', this.show)
            },
            onsend (val) {
                if (!this.id && val === '') {
                    return
                }
                this._sendAllWebSocket({
                    roomId: this.id,
                    message: val
                })
                this._getChatRoomRecord(this.id)
            },
            inChat (id, roomName) {
                this.id = id
                this.typeName = roomName
                this._getChatRoomRecord(id)
                if (this.chatRoomList.includes(id)) {
                    return
                }
                this.chatRoomList.push(id)
                this.createSocket(id)
            },
            initWebSocket () {
                // 连接错误
                this.websocket.onerror = this.setErrorMessage
                // 连接成功
                this.websocket.onopen = this.setOnopenMessage
                // 收到消息的回调
                this.websocket.onmessage = this.setOnmessageMessage
                // 连接关闭的回调
                // this.websocket.onclose = this.setOncloseMessage
                // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
                window.onbeforeunload = this.onbeforeunload
            },
            setErrorMessage () {
                console.log('WebSocket连接发生错误   状态码：' + this.websocket.readyState)
            },
            setOnopenMessage () {
                console.log('WebSocket连接成功    状态码：' + this.websocket.readyState)
            },
            setOnmessageMessage (event) {                // 根据服务器推送的消息做自己的业务处理
                // this.roomRecord = [...this.roomRecord].push(JSON.parse(event.data))
                // if (this.chatRoomList.includes(this.id)) {return}
                const data = JSON.parse(event.data)
                this.roomRecord.push({
                    avatarUrl: data.senderAvatarUrl,
                    createTime: data.date,
                    message: data.msg,
                    senderName: data.username
                })
                this.roomRecord = this.roomRecord.filter(item => item.senderName != null)

            },
            setOncloseMessage () {
                console.log('WebSocket连接关闭    状态码：' + this.websocket.readyState)
            },
            onbeforeunload () {
                this.closeWebSocket()
            },
            closeWebSocket () {
                this.websocket.close()
            },
            createSocket (id) {
                const userInfo = getUserInfo()
                const uri = `${userInfo.username}-${id}`
                this.websocket = new WebSocket('wss://wwsszz.top:2333/websocket/' + encodeURI(encodeURI(uri)))
                this.initWebSocket()
            },
            _sendAllWebSocket(data) {
              sendAllWebSocket(data).then(res => {
                  if (res.code === ERROR_NO) {
                      this._getChatRoomRecord(this.id)
                  }
              })
            },
            _getChatRoomRecord (id) {
                getChatRoomRecord(id).then(res => {
                    if (res.code === ERROR_NO) {
                        this.roomRecord = res.data.roomRecord || []
                    }
                })
            }

        },
        created () {
            this.scale = this.height / defHeight
            this.chatList = [...this.chatList, ...this.chatList, ...this.chatList, ...this.chatList]
            console.log(this.chatRoom)
        },
        mounted () {
            // console.log(this.$refs.chatcontainer)
            // this.$refs.chatcontainer.style[transform] = `scale(${this.scale}, ${this.scale})`
        },
        destroyed () {
            this.websocket.onclose = this.setOncloseMessage
        },
        components: {
            DialogBox
        }
    }
</script>

<style scoped lang="scss">
    @import "./src/common/scss/variable";
    @import "./src/common/scss/mixin";
    .chat-wrapper {
        position: fixed;
        top: 0;
        right: 0;
        height: 100%;
        width: 37px;
        z-index: 1000;
        &:hover {
            &::after {
                transform: translateX(0);
            }
            span {
                transform: translate(-25%, -50%) rotate(135deg);
            }
            .other {
                transform: translate(100%, -50%) rotate(135deg);
            }
        }
        &::after {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            border-radius: 20px 0 0 20px;
            border: 1px solid $border-color;
            opacity: 0.97;
            background-color: #fff;
            transition: all 200ms;
            transform: translateX(100%);
        }
        span {
            position: absolute;
            top: 50%;
            left: 50%;
            z-index: 1000;
            border: 11px solid transparent;
            border-right-color: #000;
            border-bottom-color: #000;
            transition: all 200ms;
            transform: translate(125%, -50%) rotate(135deg);
            cursor: pointer;
        }
        .other {
            transition: all 100ms;
            transform: translate(32%, -50%) rotate(135deg);
        }
    }
    .slide-enter-active, .slide-leave-active {
        transition: all 1s
    }

    .slide-enter, .slide-leave-to {
        transform: translate3d(100%, 0, 0)
    }

    .chat-container {
        position: fixed;
        top: 50%;
        right: 0;
        display: grid;
        grid-template-columns: 37fr 277fr 475fr;
        width: 790px;
        transform-origin: right center;
        z-index: 999;
        opacity: 0.97;
        background-color: #fff;
        border-radius: 20px 0 0 20px;

        .chat-arrow-wrapper {
            position: relative;
            height: 100%;
            width: 37px;
            border-radius: 20px 0 0 20px;
            border: 1px solid $border-color;
            span {
                position: absolute;
                top: 50%;
                left: 50%;
                border: 11px solid transparent;
                border-right-color: #000;
                border-bottom-color: #000;
                transform: translate(-75%, -50%) rotate(-45deg);
                cursor: pointer;
            }
        }

        .chat-list-wrapper {
            position: relative;
            max-width: 277px;
            width: 100%;
            box-sizing: border-box;
            background-color: rgba(255, 255, 255, .8);
            border-top: 1px solid $border-color;
            border-bottom: 1px solid $border-color;
            overflow-x: hidden;
            overflow-y: auto;
            scroll-behavior: smooth;

            &::-webkit-scrollbar {
                width: 4px;
                background: white;
            }

            &::-webkit-scrollbar-corner,
            &::-webkit-scrollbar-thumb,
            &::-webkit-scrollbar-track {
                border-radius: 4px;
            }

            &::-webkit-scrollbar-corner,
            &::-webkit-scrollbar-track {
                background-color: rgba(180, 160, 120, 0.1);
                box-shadow: inset 0 0 1px rgba(180, 160, 120, 0.5);
            }

            &::-webkit-scrollbar-thumb {
                background-color: $border-color;
            }

            .search-box {
                position: relative;
                display: flex;
                align-items: center;
                height: 61px;
                padding: 0 12px;
                box-sizing: border-box;
                border-bottom: 1px solid $border-color;

                .iconfont {
                    position: absolute;
                    top: 23px;
                    left: 20px;
                    z-index: 6;
                }

                .search-wrapper {
                    position: relative;

                    .search-input {
                        width: 215px;
                        height: 26px;
                        padding: 5px 25px;
                        border-radius: 5px;
                        box-sizing: border-box;
                        color: $font-gray;
                        border: 1px solid $border-color;
                        background-color: #ffffff;

                        &:focus {
                            outline: none;
                        }
                    }

                    .search-close::after {
                        content: 'x';
                        position: absolute;
                        top: 5px;
                        right: 6px;
                        width: 14px;
                        height: 14px;
                        line-height: 14px;
                        border-radius: 50%;
                        text-align: center;
                        font-size: 10px;
                        color: #ffffff;
                        background-color: rgb(143, 142, 148);
                        cursor: pointer;
                    }
                }

                .search-cancel {
                    padding: 4px 0;
                    margin-left: 8px;
                    line-height: 18px;
                    color: rgb(0, 118, 255);
                    font-size: 11px;
                    cursor: pointer;
                }
            }

            .chat-item {
                position: relative;
                display: flex;
                align-items: center;
                width: 100%;
                height: 61px;
                padding: 0 2px;
                box-sizing: border-box;
                border-bottom: 1px solid $border-color;
                cursor: pointer;
                &:focus-within {
                    background-color: #00ff00;
                }
                .chat-item-img {
                    width: 40px;
                    height: 40px;
                    border-radius: 50%;
                }

                .chat-info-wrapper {
                    max-width: 227px;
                    width: 100%;
                    margin-left: 6px;
                    line-height: 17px;
                    color: rgb(170, 170, 170);
                    font-size: 12px;

                    .chat-info {
                        display: flex;
                        justify-content: space-between;
                        padding-right: 8px;
                        box-sizing: border-box;
                        .chat-name {
                            font-weight: 500;
                            line-height: 22px;
                            color: $font-gray;
                            font-size: 16px;
                        }
                    }

                    .chat-content {
                        @include no-wrap;
                        padding-right: 14px;
                        box-sizing: border-box;
                    }
                }

                &:hover {
                    .chat-item-close::after {
                        content: 'x';
                        position: absolute;
                        bottom: 10px;
                        right: 12px;
                        width: 14px;
                        height: 14px;
                        line-height: 14px;
                        border-radius: 50%;
                        text-align: center;
                        font-size: 10px;
                        color: #ffffff;
                        background-color: rgb(143, 142, 148);
                        cursor: pointer;
                        transition-delay: -200ms;
                    }
                }
            }
        }

        .chat-room-wrapper {
            position: relative;
            width: 100%;
            max-width: 472px;
        }
    }
</style>
